<?php
/*ws 优化 基础类库*/
require_once '../../framework/bootstrap.inc.php';
//load()->func('cache.redis');
class Ws {
    CONST HOST = '0.0.0.0';
    CONST PORT = 8125;
    // CONST CHART = 8813;
    public $ws = null;
    public function __construct() {
        cache_clean();
        //获取缓存的用户fd数据  并删除
        $this->ws = new swoole_websocket_server(SELF::HOST, SELF::PORT);
        //,SWOOLE_PROCESS, SWOOLE_SOCK_TCP | SWOOLE_SSL
        $this->ws->set([
            'ssl_cert_file' => './key2.pem',
            'ssl_key_file' => './key1.key',
            'worker_num' => 4,
            'task_worker_num' => 4,
            'heartbeat_check_interval' => 60,
            'heartbeat_idle_time' => 120,
        ]);
        $this->ws->on('start',[$this,'onStart']);
        // $this->ws->listen(SELF::HOST,SELF::CHART,SWOOLE_SOCK_TCP);
        $this->ws->on('open',[$this,'onOpen']);
        $this->ws->on('message',[$this,'onMessage']);
        $this->ws->on('close',[$this,'onClose']);

        $this->ws->on("task", [$this, 'onTask']);
        $this->ws->on("finish", [$this, 'onFinish']);

        $this->ws->start();

        $client = new swoole_client(SWOOLE_SOCK_TCP | SWOOLE_ASYNC);
        file_put_contents('heartbeat1111.txt',json_encode($client));
        Swoole\Timer::tick(3000, function () use ($client) {
            $data = "heartbeat";
            file_put_contents('heartbeat.txt','心跳');
            $client->send($data);
        });

    }

    public function onStart($server) {
        swoole_set_process_name("live_master");
    }

    public function onOpen($ws,$request) {
        $sonid = $request->get['sonid'];
        $data = cache_read('livemember'.$sonid);
        if(empty($data)){
            $dat[] = $request->fd;
            cache_write('livemember'.$sonid,$dat);
        }else{
            if(!in_array($request->fd,$data)){
                array_push($data,$request->fd);
                cache_write('livemember'.$sonid,$data);
            }
        }
        //返回实时人数
        $rangnum = rand(200,250);
        $totalnum = count($data)+$rangnum;
        $rdata = ['totalnum'=>$totalnum];
        $datas = [
            'fd' => $data,
            'message' =>json_encode($rdata),
        ];
        file_put_contents('open.txt',json_encode($datas));
        $ws->task($datas);
    }

    /**
     * @param $serv
     * @param $taskId
     * @param $workerId
     * @param $data
     */
    public function onTask($serv, $taskId, $workerId, $data) {
        // 分发 task 任务机制，让不同的任务 走不同的逻辑
        foreach($data['fd'] as $k=>$v){
            $serv->push($v,$data['message']);
        }
        file_put_contents('task.txt',json_encode($data));
        return 'OK'; // 告诉worker
    }
    /**
     * @param $serv
     * @param $taskId
     * @param $data
     */
    public function onFinish($serv, $taskId, $data) {
        echo "taskId:{$taskId}\n";
        echo "finish-data-sucess:{$data}\n";
    }

    public function onMessage($ws,$frame) {
        $sonid = json_decode($frame->data,true)['sonid'];
        $fdlist = cache_read('livemember'.$sonid);
        $data = [
            'task' => 1,
            'fd' => $fdlist,
            'message' => $frame->data,
        ];
        $ws->task($data);
        /*$sonid = json_decode($frame->data,true)['sonid'];
        $data = cache_read('livemember'.$sonid);
        foreach($data as $k=>$v){
            $ws->push($v,$frame->data);
        }*/
    }
    
    public function onClose($ws,$fd) {
        $search = cache_search('livemember');
        file_put_contents('search1.txt',json_encode($search));
        foreach($search as $k=>$v){
            if(is_array($v)){
                if(in_array($fd,$v)){
                    unset($v[array_search($fd,$v)]);
                }
            }
            cache_write($k,$v);   
        }
    }

}
$object = new Ws();